<template>
	<view class="bigView">
		<canvas
		  canvas-id="countdownCanvas"
		  class="circle-countdown"
		  :style="{ width: '180rpx', height: '180rpx' }"
		  v-if="countdown>0 && type == 1 && Object.keys(this.userInfo).length>0"
		></canvas>
		<view style="padding: 16px;overflow-y: auto">
			<!-- <rich-text :nodes="htmlValue"></rich-text> -->
			<!-- <u-parse :content="htmlValue" :lazyLoad="true"></u-parse> -->
			<block v-if="sourceType==3">
				<view class="item">
					<view class="title">{{result.theme}}</view>
					<view class="line"></view>
					<view class="stepView">
						<u-steps current="-1" direction="column" inactive-color="#247BFD">
							<u-steps-item :title="item2.title" v-for="(item2,index2) in result.list" :key="index2">
								<text class="slotIconText" slot="icon">{{index2+1}}</text>
							</u-steps-item>
						</u-steps>
					</view>
				</view>
			</block>
			<block v-else>
				<u-parse :content="htmlValue"></u-parse>
				<view class="bottomView" v-if="htmlValue && type==1">
					<view></view>
					<view style="display: flex;flex-direction: row;padding-right: 10px;align-items: center;font-size: 14px;">
						<button open-type="share" class="shareBtn" style="border:none;color: black;" plain type="primary" v-if="Object.keys(userInfo).length>0">
						<!-- 分享 -->
							<u-icon name="share" size="20"></u-icon>
						</button>
						<view style="margin-right: 20px;" @click="shareHandle(item)" v-else>
							<u-icon name="share" size="20"></u-icon>
						</view>
						<view @click="giveThumbsHandle(item)">
							<u-icon name="heart" size="20"></u-icon>
						</view>
					</view>
				</view>
			</block>
			
		</view>
		<view></view>
	</view>
</template>

<script>
	import noti from '@/api/noti.js'
	import news from '@/api/news.js'
	import carbonNeutrality from '@/api/carbonNeutrality.js'
	import jiaRenReport from '@/api/jiaRenReport.js'
	import workGuide from '@/api/workGuide.js'
	import club from '@/api/club.js'
	import mine from '@/api/mine.js'
	export default{
		components:{
			
		},
		data(){
			return {
				bottom:0,
				type:0,//
				currentId:'',
				result:{},
				htmlValue:'',
				timer: null,
				timestamp:15,
				remainingTime: 15, // 60 秒
				userInfo:{},
				sourceType:'',//来源：1、嘉园风情与航嘉文化  2、
				
				totalSeconds: 15, // 总倒计时秒数
				countdown: 15, // 当前倒计时秒数
				timer: null, // 定时器 ID
				canvasWidth: 80, // 画布宽度
				canvasHeight: 80, // 画布高度
				radius: 35, // 圆形半径
				circumference: 0, // 圆形周长
				dashoffset: 0, // 进度条偏移量
				ctx: null, // 画布上下文
				isAnimating: false // 动画状态标志
			}
		},
		mounted() {
			uni.getSystemInfo({success: (e) => {
				let custom = wx.getMenuButtonBoundingClientRect();
				this.bottom = custom.bottom;
			}})
			this.$nextTick(() =>{
				// 获取画布上下文
				this.ctx = uni.createCanvasContext('countdownCanvas', this);
				// 计算圆形周长
				this.circumference = 2 * Math.PI * this.radius;
				this.dashoffset = this.circumference;
				// 绘制初始状态的圆形
				this.drawCircle();
				
				this.initUserInfo()
			})
		},
		onLoad(options) {
			if(options.id){
				this.type = options.type??'';
				this.sourceType = options.sourceType;
				this.currentId = options.id??'';
				// this.queryByIdRequest()
			}else{
				this.sourceType = options.sourceType;
			}
			this.queryByIdRequest()
			// if (this.type == 1) {
			// 	setTimeout(() => {
			// 		this.startCountdown();
			// 	}, 1000)
			// }
			if (this.type != 0) {
				setTimeout(() => {
					this.startCountdown2();
				}, 1000)
			}
		},
		onShareAppMessage() {
			const _this = this; // 保存 this 上下文
			if(Object.keys(this.userInfo).length==0){
				uni.redirectTo({
					url: '/pages/login/login'
				})
				return
			}
			if(_this.type == 1){// 嘉园风情
				carbonNeutrality.forward2({id:_this.result.id}).then(res =>{
					uni.showToast({
						title:"分享成功"
					})
				}).catch(err =>{
					
				})
			}
			return{
				title: this.result.theme,
				path: '/packageHome/pages/homeDetail/index?id='+this.currentId+"&type="+this.type,
				success(res) {
					console.log('分享成功', res);
					// if(_this.type == 1){// 嘉园风情
					// 	carbonNeutrality.forward2({id:_this.result.id}).then(res =>{
					// 		uni.showToast({
					// 			title:"分享成功"
					// 		})
					// 	}).catch(err =>{
							
					// 	})
					// }
				},
				fail(err) {
					console.error('分享失败', err);
					uni.showModal({
						title:err
					})
				}
			}
		},
		onShareTimeline() {
			return {
				title:'嘉园风情',
				path:'/packageHome/pages/homeDetail/index?id='+this.currentId+"&type="+this.type
			}
		},
		methods:{
			startCountdown2() {
			  if (this.isAnimating) return; // 如果动画已经在运行，则直接返回
			  this.isAnimating = true; // 标记动画开始
			  this.countdown = this.totalSeconds;
			  this.dashoffset = this.circumference;
			  this.animate();
			},
			animate() {
			  if (this.countdown <= 0) {
			    this.stopCountdown(); // 倒计时结束
			    return;
			  }
			
			  // 更新倒计时
			  this.countdown--;
			  const progress = this.countdown / this.totalSeconds;
			  this.dashoffset = this.circumference * progress;
			
			  // 绘制圆形
			  this.drawCircle();
			
			  // 继续倒计时
			  this.timer = setTimeout(() => {
			    this.animate();
			  }, 1000);
			},
			stopCountdown() {
			  clearTimeout(this.timer); // 清除定时器
			  this.timer = null;
			  this.isAnimating = false; // 标记动画结束
			  // uni.showToast({
			  //   title: '倒计时结束！',
			  //   icon: 'none'
			  // });
			  this.browseRequest()
			},
			drawCircle() {
			  if (!this.ctx) return;
			  const ctx = this.ctx;
			  const centerX = this.canvasWidth / 2;
			  const centerY = this.canvasHeight / 2;
			
			  // 清空画布
			  ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
			
			  // 绘制橘黄色背景圆
			  ctx.beginPath();
			  ctx.arc(centerX, centerY, this.radius, 0, 2 * Math.PI);
			  ctx.fillStyle = '#F5F5F5';
			  ctx.fill();
			
			  // 绘制背景圆
			  ctx.beginPath();
			  ctx.arc(centerX, centerY, this.radius, 0, 2 * Math.PI);
			  ctx.strokeStyle = '#e0e0e0';
			  ctx.lineWidth = 10;
			  ctx.stroke();
			
			  // 绘制进度圆
			  ctx.beginPath();
			  const startAngle = -Math.PI / 2;
			  // const endAngle = startAngle - 2 * Math.PI * (1 - this.dashoffset / this.circumference); // 逆时针方向
			  const endAngle = startAngle - 2 * Math.PI * (1 - this.dashoffset / this.circumference);
			  ctx.arc(centerX, centerY, this.radius, startAngle, endAngle, true); // true 表示逆时针
			  ctx.strokeStyle = this.getColor();
			  ctx.lineWidth = 10;
			  ctx.lineCap = 'round';
			  ctx.stroke();
			
			  // 绘制倒计时文本
			  ctx.font = '20px Arial';
			  ctx.fillStyle = 'black';
			  ctx.textAlign = 'center';
			  ctx.textBaseline = 'middle';
			  ctx.fillText(this.countdown, centerX, centerY);
			
			  // 绘制到画布
			  ctx.draw(true); // 使用 true 表示保留上一次绘制的内容
			},
			getColor() {
			  const ratio = this.countdown / this.totalSeconds;
			  // if (ratio > 0.6) {
			    return '#247BFD';
			  // } else if (ratio > 0.3) {
			    // return 'orange';
			  // }
			  // return 'red';
			},
			click(item) {
				this.newsListRequest(item.index+1)
			},
			scrolltolower() {
				// this.loadmore()
			},
			sureHandle(){
				uni.navigateBack()
			},
			queryByIdRequest(){
				if (this.sourceType == 1) { // 嘉园风情与航嘉文件详情
					carbonNeutrality.carbonNeutralityQueryById({id:this.currentId,carbonType:this.type}).then(res =>{
						this.result = res;
						this.htmlValue = this.result.content;
					})
				}else if (this.sourceType == 2) {// 嘉人报道
					jiaRenReport.queryById({id:this.currentId}).then(res =>{
						this.result = res;
						this.htmlValue = this.result.content;
					})
				}else if (this.sourceType == 3) {// 办事指南
					workGuide.queryById({id:this.currentId}).then(res =>{
						this.result = res;
						this.result.list = JSON.parse(res.content)
						this.htmlValue = this.result.content;
						// let records = res.records;
						// for(let i=0;i<records.length;i++){
						// 	let dataList = [];
						// 	dataList = JSON.parse(records[i].content)
						// 	records[i]['list'] = dataList
						// }
					})
				}else if (this.sourceType == 4) {// 积分规则详情
					uni.setNavigationBarTitle({
						title:'积分规则'
					})
					mine.getRule({}).then(res =>{
						this.result = res;
						this.htmlValue = this.result.content;
					})
				}
				
				
			},
			initUserInfo(){
				const userInfo = uni.getStorageSync("userInfo")
				if(userInfo){
					this.userInfo = JSON.parse(userInfo)
				}				
			},
			backHandle(){
				if(this.timer != null){
					clearInterval(this.timer);
				}
			},
			// 事件触发，每秒一次
			change(timestamp) {
				console.log(timestamp);
			},
			formattedTime() {
			  const seconds = this.remainingTime % 60;
			  return `${seconds < 10 ? '0' + seconds : seconds}`;
			},
			startCountdown() {
				if(Object.keys(this.userInfo).length==0){
					return
				}
			      this.timer = setInterval(() => {
			        if (this.remainingTime > 0) {
			          this.remainingTime--;
					  console.log("-------"+this.remainingTime)
			        } else {
			          clearInterval(this.timer);
			          this.remainingTime = 0;
					  this.browseRequest()
			        }
			      }, 1000)
			},
			browseRequest(){
				if(this.type == 1){// 新闻动态
					carbonNeutrality.browse2({id:this.result.id}).then(res =>{
						
					}).catch(err =>{
					
					})
				}
				
			},
			giveThumbsHandle(){// 点赞
				if(Object.keys(this.userInfo).length==0){
					uni.redirectTo({
						url: '/pages/login/login'
					})
					return
				}
				uni.showLoading({
					title:"正在执行..."
				})
				if(this.type == 1){// 新闻动态
					carbonNeutrality.giveThumbs2({id:this.result.id}).then(res =>{
						uni.hideLoading()
						uni.showToast({
							title:"操作成功"
						})
					}).catch(err =>{
						uni.hideLoading()
					})
				}
				
			},
			shareHandle(item){
				if(Object.keys(this.userInfo).length==0){
					uni.redirectTo({
						url: '/pages/login/login'
					})
					return
				}
			},
		},
		onReady() {
			
		}
	}
</script>

<style lang="scss" scoped>
.bigView{
	width: 100vw;
	height: 100vh;
	background-color: #F7F7F7;
	display: flex;
	flex-direction: column;
}
.bottomView{
	width: 100%;
	height: 40px;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
}
.shareBtn{
	background-color: white;
	border: none;
	font-size: 14px;
}
.countDownView{
	position: fixed;
	width: 50px;
	height: 50px;
	background-color: #FFFFFF;
	right: 5px;
	bottom: 60px;
	border-radius: 25px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 12;
	box-shadow: 1px 1px #FFFFFF;
}

.item{
	width: calc(100vw - 32px);
	display: flex;
	flex-direction: column;
	border-radius: 12px;
	background-color: white;
	// margin-left: 16px;
	margin-top: 8px;
	.title{
		height: 54px;
		width: calc(100vw - 32px);
		display: flex;
		align-items: center;
		padding-left: 16px;
	}
	.line{
		height: 0.5px;
		background-color: #F7F7F7;
		width: calc(100vw - 32px);
	}
	.stepView{
		padding: 16px;
	}
	.slotIconText{
		width: 21px;
		height: 21px;
		background-color: #247BFD;//$u-warning;
		border-radius: 100px;
		font-size: 12px;
		color: #fff;
		line-height: 21px;
		text-align: center;
	}
}

table, td, th {
  border-color: #ddd;
  border-width: 1px;
  border-style: solid;
}
.circle-countdown-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  // height: 100vh;
  background-color: red;
}

.circle-countdown {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20px;
  z-index: 10;
  position: fixed;
  right: 0rpx;
  bottom: 60rpx;
  // background-color: red;
}
</style>